package com.yifeng.repo.base.security.auth;

import com.gomcarter.frameworks.base.common.AssertUtils;
import com.yifeng.repo.base.params.ConsoleParam;
import com.yifeng.repo.base.security.auth.constant.SecurityTypeEnum;
import com.yifeng.repo.base.security.context.params.SecurityCheckParam;
import com.yifeng.repo.base.utils.action.BizCacheAction;

import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by daibing on 2023/8/24.
 */
public class SecurityCheckerFactory {
    private static final ConcurrentMap<SecurityTypeEnum, SecurityChecker> IMPL_MAPPING = new ConcurrentHashMap<>(4);

    static {
        ServiceLoader<SecurityChecker> serviceLoader = ServiceLoader.load(SecurityChecker.class);
        for (SecurityChecker service : serviceLoader) {
            try {
                IMPL_MAPPING.put(service.securityType(), service);
            } catch (Exception e) {
                // ignore error when load spring bean
            }
        }
    }

    public static SecurityChecker get(SecurityTypeEnum securityType) {
        SecurityChecker checker = IMPL_MAPPING.get(securityType);
        AssertUtils.notNull(checker, "没有匹配到该类型的实现：" + securityType);
        return checker;
    }

    public static void init(List<SecurityCheckParam> securityCheckParams,
                            Map<SecurityTypeEnum, ConsoleParam> securityType2ConsoleParam,
                            BizCacheAction bizCacheAction) {
        securityCheckParams.forEach(s -> {
            SecurityChecker checker = IMPL_MAPPING.get(s.getSecurityType());
            checker.init(s, securityType2ConsoleParam.get(s.getSecurityType()), bizCacheAction);
        });
    }

}
